#!/usr/bin python
# -*- coding: utf-8 -*-
# @Time    : 2023/6/16 16:16
# @Author  : hhr

"""
解压压缩包文件，移动到对应的文件夹
"""
import json
import os, re, time, zipfile, shutil, xlwt

import requests
from retrying import retry
from configuration_files.setting import UrlContainer
from configuration_files.Connect_files import DbConnect
from 识别办登费用 import start_identify
from UploadFiles import upload_pdf_file


class unzip_file():
    def __init__(self, environment):
        self.db = DbConnect().system_db()
        self.cursor = self.db.cursor()
        self.token = upload_pdf_file().token
        self.online_db = DbConnect().big_data_conn()
        self.online_cursor = self.online_db.cursor()
        self.headers = {"Accept": "application/json"}
        self.environment = environment
        self.pendingData = []

    # 创建异常需要人工处理的表
    def dataToProcessedManually(self, listData, today_date):
        pendingWork = xlwt.Workbook()
        abnormalExc = pendingWork.add_sheet("sheet1")
        abnormalExc.write(0, 0, '文件名')
        abnormalExc.write(0, 1, '异常情况')
        abnormalExc.write(0, 2, '流程状态')
        for i in range(len(listData)):
            abnormalExc.write(i + 1, 0, listData[i]['wjm'])
            abnormalExc.write(i + 1, 1, listData[i]['ycqk'])
            abnormalExc.write(i + 1, 2, listData[i]['lczt'])

        pendingWork.save(r'D:\python文件\cpc文件处理\decompressdailycpcfiles\上传文件记录\\'+today_date+'需人工处理.xls')


    def parse_pdf(self, pathZip, pdf_main_path, date, url_dir):
        """
        处理压缩包
        :param pathZip:             压缩包路径
        :param pdf_main_path:       PDF文件夹路径
        :return:
        """
        # D:\工作文件\桌面文件\工作用文件\自动化\CPC纯代码下载文件\20230206\压缩包
        file_list = os.listdir(pathZip)

        # ========================================= 创建解压后文件存放的文件夹 =========================================
        bz_path, bd_path, st_path, zlzs_path, other_path, huizhi_path, day_bd_path = self.create_path(pdf_main_path)

        # ========================================= 解压第一层压缩包 =========================================
        for file_ in file_list:
            inst = file_.split('_')[1].split('.')[0]  # inst 接收文件端口
            print(f"========================== 开始处理 {inst} 端口文件 ==========================", file_)
            # ========================================= 保存第一层压缩包解压之后的压缩包 =========================================
            first_folder = os.path.join(pathZip, inst)
            if not os.path.exists(first_folder):
                os.mkdir(first_folder)

            zipFile = zipfile.ZipFile(os.path.join(pathZip, file_))  # 压缩包路径
            zipFileList = zipFile.namelist()  # 获取压缩包里所有文件      解压的是最原始的压缩包.XHHG或者.XH后缀
            for f in zipFileList:
                zipFile.extract(f, first_folder)  # 循环解压文件到指定目录
            zipFile.close()

            # ========================================= 解压第二层压缩包 =========================================
            first_zip_list = os.listdir(first_folder)
            for first_zip in first_zip_list:
                SecondPath = os.path.join(first_folder, first_zip)
                SecondZipFile = zipfile.ZipFile(SecondPath)  # 开始单个解压第二层压缩包
                SecondZipFileList = SecondZipFile.namelist()  # 获取第二层单个压缩包里所有文件

                SecondSavePath = os.path.join(pathZip, 'temp')
                if not os.path.exists(SecondSavePath):
                    os.mkdir(SecondSavePath)
                for file_li in SecondZipFileList:
                    if '/' not in file_li:
                        SecondZipFile.extract(file_li, SecondSavePath)  # 循环解压文件到指定目录

                # ========================================= 修改通知书名称 =========================================
                xml_path = os.path.join(SecondSavePath, 'list.xml')
                save_file_name, sqh, tzs_name, tzs_bm, wjmc = self.pdf_name(xml_path, inst)

                if "专利证书" in save_file_name:
                    if not os.path.exists(zlzs_path):
                        os.mkdir(zlzs_path)
                    old_file_name = os.path.join(SecondSavePath, f"{sqh}.pdf")
                    fille_type_path = zlzs_path
                elif "回执" in save_file_name:
                    if not os.path.exists(huizhi_path):
                        os.mkdir(huizhi_path)
                    old_file_name = ""
                    # MainFunc(os.path.join(SecondSavePath, f"{save_file_name}.pdf"), os.path.join(SecondSavePath, '200105.xml'))
                    fille_type_path = huizhi_path
                else:
                    old_file_name = os.path.join(SecondSavePath, f"{tzs_bm}.pdf")
                    if "审查意见" in save_file_name or '补正' in save_file_name or '驳回' in save_file_name:
                        if not os.path.exists(bz_path):
                            os.mkdir(bz_path)
                        fille_type_path = bz_path
                    elif '减缴审批' in save_file_name or "专利申请受理" in save_file_name:
                        if not os.path.exists(st_path):
                            os.mkdir(st_path)
                        fille_type_path = st_path
                    elif '办理登记' in save_file_name:
                        if not os.path.exists(bd_path):
                            os.mkdir(bd_path)
                        fille_type_path = bd_path
                    else:
                        if not os.path.exists(other_path):
                            os.mkdir(other_path)
                        fille_type_path = other_path

                if old_file_name:
                    # save_file_name.replace("/", "_")
                    new_file_name = os.path.join(SecondSavePath, save_file_name + '.pdf')
                    os.rename(old_file_name, new_file_name)
                    shutil.move(new_file_name, fille_type_path)
                    new_file_path = os.path.join(fille_type_path, save_file_name + '.pdf')
                    # 解压一个文件，上传一个文件
                    # print("当前处理的文件是: ", new_file_path)
                    # if save_file_name not in ['2025-02-26_W202104120857_自风干绘图板及绘图工具_缴费通知书_2017200790235_XHHG', '2025-02-26_W202104120858_一种绘图板及绘图用具_缴费通知书_2017200764207_XHHG', '2025-02-23_B202403300070_一种新型洗胃管和洗胃桶装置_收费减缴审批通知书_2024208466051_XHHG', '2025-02-26_A202201170058_一种改良型约束手帕_退款审批通知书_2022202635447_XHHG', '26_B202410170259F_一种吸入装置智能培训方法及相关装置_发明专利申请初步审查合格通知书_2025101349431_XHHG', '2025-02-25_B202412130325F_膈肌电刺激方法及相关装置_专利申请受理通知书_2025102105171_XHHG', '2025-02-25_B202412130325F_膈肌电刺激方法及相关装置_收费减缴审批通知书_2025102105171_XHHG']:
                    #     # ------------------------------- 上传通知书 -----------------------------------
                    #     self.upload_pdf_files(new_file_path, date, url_dir, save_file_name)
                    # else:
                    #     print("=============++++++++++++++++++", save_file_name)
                    # ------------------------------- 上传通知书 -----------------------------------
                    self.upload_pdf_files(new_file_path, date, url_dir, save_file_name)
                    print("\n")
                    if wjmc:
                        new_fj_name = os.path.join(SecondSavePath, f"{wjmc}.pdf")
                        save_file_name_1 = save_file_name.replace("办理登记手续", "授权")
                        rename_after_name = os.path.join(SecondSavePath, save_file_name_1 + '.pdf')
                        os.rename(new_fj_name, rename_after_name)
                        shutil.move(rename_after_name, fille_type_path)

                SecondZipFile.close()
                shutil.rmtree(SecondSavePath)

            shutil.rmtree(first_folder)
            print(f"========================== {inst} 端口文件处理了完毕 ==========================")
        if os.path.exists(bd_path):
            print("=========================== 开始处理今日需上传办登文件 ===========================")
            if not os.path.exists(day_bd_path):
                os.mkdir(day_bd_path)
            # 复制
            self.copy_func(bd_path, day_bd_path)
            print(f"========================== 开始生成办登Excel文件,上传办登文件 ==========================")
            self.create_excel(bd_path, date, day_bd_path, url_dir['dfbz'])

    def upload_pdf_files(self, pdf_path, today_date, url_dir, file):
        """
        所有的文件都放入此处上传
        """
        if '专利申请受理通知书' in file:
            # 上传受通文件
            self.upload_st(pdf_path, file, today_date, url_dir['st'])
        elif '专利证书' in file:
            # 上传证书
            self.upload_patent_zs(pdf_path, file, today_date, url_dir['zs'])
        elif '专利权终止通知书' in file or '手续合格通知书' in file:
            # 上传异常文件
            self.upload_abnormal(pdf_path, file, today_date, url_dir['yc'])
        elif '补正通知书' in file or "复审通知书" in file or '审查意见通知书' in file or '发明专利申请初步审查' in file or '驳回决定' in file or '进入实质审查' in file or '电子申请' in file:
            item = {"file": pdf_path, "name": file,
                    "type": "1" if '审查意见通知书' in file else "2" if '补正通知书' in file or "复审通知书" in file else "3" if '发明专利申请初步审查' in file else "4" if '进入实质审查' in file else "5"}
            sqh = file.split("_")[-2]
            id = self.get_id(sqh)
            print("=====================sqh: ", sqh)
            print("=====================id: ", id)
            self.upload_files(item, id, today_date, url_dir['dfbz'])
        else:
            if "减缴审批通知书" not in file and "办理登记" not in file and "授权通知书" not in file:
                self.upload_other_files(pdf_path, file, today_date, url_dir['ot'])

    def copy_func(self, bd_path, day_bd_path):
        """复制操作
        :param bd_path:
        :param day_bd_path: 目标文件路径
        """
        for file_name in os.listdir(bd_path):
            file_path = os.path.join(bd_path, file_name)  # 办登文件路径
            new_file_path = os.path.join(day_bd_path, file_name)  # 办登文件路径
            shutil.copy(file_path, new_file_path)

    def pdf_name(self, path, inst):
        """
        获取xml中的文件名称
        :param path: XML文件路径
        :param inst: 文件获取端口：XH，协和；XHHG，信合红谷
        :return:
        """
        with open(path, 'r', encoding='utf-8')as f:
            content = f.read()
            sqr = ''.join(re.findall(r'<SHENQINGR>(.*?)</SHENQINGR>', content))
            sqr = sqr[:4] + '-' + sqr[4:6] + '-' + sqr[6:8]
            sqh = ''.join(re.findall(r'<SHENQINGH>(.*?)</SHENQINGH>', content))
            if sqh == '':
                sqh = '未获取到申请号'
            if sqr == '':
                sqr = '未获取到申请日'
            order_number = self.get_order(sqh)
            if len(order_number) > 0:
                bh = order_number[0][0]
            else:
                bh = ''.join(re.findall(r'<NEIBUBH>(.*?)</NEIBUBH>', content))
                if bh == '':
                    bh = '未获取到编号'
            fm_name = ''.join(re.findall(r'<FAMINGMC>(.*?)</FAMINGMC>', content))
            if fm_name == '':
                fm_name = '未获取到发明名称'
            tzs_name = ''.join(re.findall(r'<TONGZHISMC>(.*?)</TONGZHISMC>', content))
            if tzs_name == '':
                tzs_name = '未获取到通知书名称'
            fwr = ''.join(re.findall(r'<FAWENR>(.*?)</FAWENR>', content))
            fwr = fwr[:4] + '-' + fwr[4:6] + '-' + fwr[6:8]

            tzs_bm = ''.join(re.findall(r'<TONGZHISBM>(.*?)</TONGZHISBM>', content))

            if fwr == '':
                fwr = '未获取到发文日'
            if '办理登记手续通知书' in content or '专利证书' in content:
                file_save_name = fwr + '_' + bh + '_' + fm_name + '_' + tzs_name + '_' + sqh + '_' + inst
            elif '补正' in content or '审查意见' in content or '驳回' in content:
                file_save_name = fwr + '_' + bh + '_' + fm_name + '_' + tzs_name + '_' + sqh + '_' + inst
            elif "申请受理通知书" in content or "收费减缴审批通知书" in content:
                file_save_name = sqr + '_' + bh + '_' + fm_name + '_' + tzs_name + '_' + sqh + '_' + inst
            elif '电子申请' in content:
                file_save_name = fwr + "_" + sqh + "_" + fm_name + "_" + tzs_name + "_" + inst
            else:
                file_save_name = fwr + '_' + bh + '_' + fm_name + '_' + tzs_name + '_' + sqh + '_' + inst

            wjmc = ""
            if "办理登记" in tzs_name:
                wjmc = ''.join([i for i in re.findall(r'<WENJIANMC>(.*?)</WENJIANMC>', content) if "通知书" in i])
        return file_save_name.replace("/", "_"), sqh, tzs_name, tzs_bm, wjmc

    def get_order(self, application_number):
        """获取订单编号"""
        sql = "select order_number from finals where application_number like '%{}%'".format(application_number)
        self.cursor.execute(sql)
        content = self.cursor.fetchall()
        return content

    def create_path(self, main_pdf):
        """拼接文件存放路径"""
        bz_path = main_pdf + '\补正答复'
        bd_path = main_pdf + '\办理登记'
        st_path = main_pdf + '\受通费减'
        zlzs_path = main_pdf + '\专利证书'
        other_path = main_pdf + '\其他文件'
        huizhi_path = main_pdf + "\电子回执"
        bd_path_1 = main_pdf + "\今日需上传办登"
        return bz_path, bd_path, st_path, zlzs_path, other_path, huizhi_path, bd_path_1

    def get_id(self, sqh):
        sql = "select id from finals where application_number like '%{}%'".format(sqh)
        self.cursor.execute(sql)
        content = self.cursor.fetchall()
        try:
            id = content[0][0]
        except:
            id = ""
        return id

    def insert_into_CPCtable(self, item):
        sql = f"insert into CPCFlieUploadResult (fwr,order_number,case_name,file_type,sqh,port,file_extension,file_name,upload_time,result,wj_type) values (" \
              f"'{item['fwr']}','{item['order_number']}','{item['case_name']}','{item['file_type']}','{item['sqh']}','{item['port']}','{item['file_extension']}','{item['file_name']}','{item['upload_time']}','{item['result']}','{item['wj_type']}')"
        try:
            self.online_cursor.execute(sql)
            self.online_db.commit()
        except Exception as e:
            print(sql)
            print(f'error:{str(e)}, 保存上传信息至数据库失败...')

    def save_upload_message(self, file_name, wj_type, result):
        """
        保存上传记录  2023-06-21_A202302240198F_一种吞咽困难患者用鼻饲管护理装置_专利申请受理通知书_202310738404X_XHHG.pdf
                    2023-06-30_2-C-N-2020042700750_一种新型粪便标本采样盒_缴费通知书_2020209047502_XH.pdf
        """
        file_name_split_li = file_name.split('_')
        now_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        item = {}
        item['fwr'] = file_name_split_li[0]
        item['order_number'] = file_name_split_li[1]
        item['case_name'] = file_name_split_li[2]
        item['file_type'] = file_name_split_li[3]
        item['sqh'] = file_name_split_li[4]
        item['port'] = file_name_split_li[5].split('.')[0]
        item['file_extension'] = 'pdf'
        item['file_name'] = file_name
        item['upload_time'] = now_time
        item['result'] = result
        item['wj_type'] = wj_type
        print('item:', item)
        self.insert_into_CPCtable(item)  # 保存到数据库文件上传记录
        if '授权通知书' in file_name:
            self.update_money_warning_table(item)

    def update_money_warning_table(self, item):
        sql = f"update MoneyWarning set fw_date='{item['fwr']}' where sqh='{item['sqh']}'"
        try:
            self.online_cursor.execute(sql)
            self.online_db.commit()
        except Exception as e:
            print(sql)
            print(f'error:{str(e)},更新授权发文日至数据库失败...')

    def create_excel(self, pdf_path, today_date, day_bd_path, bd_url):
        item_list = start_identify(pdf_path)
        workbook = xlwt.Workbook()
        sheet = workbook.add_sheet("sheet1")
        sheet.write(0, 0, '编号')
        sheet.write(0, 1, '发文日')
        sheet.write(0, 2, '申请号')
        sheet.write(0, 3, '案件名称')
        sheet.write(0, 4, '申请人')
        sheet.write(0, 5, '年费金额')
        sheet.write(0, 6, '专利类型')
        sheet.write(0, 7, '备注')
        sheet.write(0, 8, '申请日')
        sheet.write(0, 9, '截止日')
        for i in range(len(item_list)):
            sheet.write(i + 1, 0, item_list[i]['ordr_number'])
            sheet.write(i + 1, 1, item_list[i]['fwr'])
            sheet.write(i + 1, 2, item_list[i]['申请号'])
            sheet.write(i + 1, 3, item_list[i]['发明名称'])
            sheet.write(i + 1, 4, item_list[i]['专利权人'])
            sheet.write(i + 1, 5, item_list[i]['总计'])
            sheet.write(i + 1, 6, item_list[i]['zl_type'])
            sheet.write(i + 1, 7, item_list[i]['费用明细'])
            sheet.write(i + 1, 8, item_list[i]['sqr'])
            sheet.write(i + 1, 9, item_list[i]['截止日'])

            bd_file = f"{item_list[i]['fwr']}_{item_list[i]['ordr_number']}_{item_list[i]['发明名称']}_办理登记手续通知书_{item_list[i]['申请号']}_{item_list[i]['inst']}.pdf"
            st_file = f"{item_list[i]['fwr']}_{item_list[i]['ordr_number']}_{item_list[i]['发明名称']}_授权通知书_{item_list[i]['申请号']}_{item_list[i]['inst']}.pdf"
            files = {'file': open("{}".format(os.path.join(day_bd_path, st_file)), "rb"),
                     'file3': open("{}".format(os.path.join(day_bd_path, bd_file)), "rb")}
            id = self.get_id(item_list[i]['申请号'])
            if id:
                headers = {
                    "Accept": "application/json",
                }
                data = {
                    'finals': id,
                    'type': "6",
                    'token': self.token,
                    'num': item_list[i]['zl_type'] + item_list[i]['费用明细'].split("年费")[0] + "年费",  # 年费名称， 示例：实用新型专利第2年年费
                    'close_date': item_list[i]['截止日'],  # 缴费截至日
                    'money': item_list[i]['总计'],  # 年费金额
                }
                url = bd_url.format(id)
                print("办理登记路由： ", url)
                r = requests.post(url=url, data=data, files=files, headers=headers, verify=False)
                res_dict = json.loads(r.text)
                if res_dict['status'] == 'success':
                    result = '上传成功！'
                    with open(f'./上传文件记录/{today_date}上传文件成功.txt', 'a+') as f:
                        f.write(f'{files}\n')
                        f.write(f'{data}\n')
                        f.write(f'{result}\n')
                        f.write('\n')
                    try:
                        self.save_upload_message(bd_file, "6", result)
                    except Exception as e:
                        print(f'创建上传信息失败,{str(e)}')
                else:
                    print(r.text)
                    result = res_dict['message']

                    erroritem = {}
                    erroritem['wjm'] = f'{files}'
                    erroritem['ycqk'] = f'{result}'
                    erroritem['lczt'] = '流程为杨锦'
                    self.pendingData.append(erroritem)

                    with open(f'./上传文件记录/{today_date}需人工处理.txt', 'a+') as f:
                        f.write(f'{files}\n')
                        f.write(f'{result}\n')
                        f.write(f'流程为杨锦\n')
                        f.write('\n')
                    try:
                        self.save_upload_message(bd_file, "6", result)
                    except Exception as e:
                        print(f'创建上传信息失败,{str(e)}')
            else:
                erroritem = {}
                erroritem['wjm'] = f'{files}'
                erroritem['ycqk'] = f'文件id：{id}'
                erroritem['lczt'] = '流程为杨锦'
                self.pendingData.append(erroritem)
                with open(f'./上传文件记录/{today_date}需人工处理.txt', 'a+') as f:
                    f.write(f'{files}\n')
                    f.write(f'文件id：{id}\n')
                    f.write(f'流程为杨锦\n')
                    f.write('\n')
        save_excel_path = os.path.join(day_bd_path, "今日需上传办登.xlsx")
        workbook.save(save_excel_path)

    def upload_st(self, file, file_name, today_date, url):
        """
        该接口为上传受通文件接口 file: 文件路径、file_name: 证书名
        """
        files = {'file': open("{}".format(file), "rb")}
        data = {'token': self.token, 'marks': '1'}
        r = requests.post(url=url, files=files, data=data, headers=self.headers, verify=False)
        res_dict = json.loads(r.text)
        if res_dict['status'] == 'success':
            result = '上传成功！'
            with open(f'./上传文件记录/{today_date}上传文件成功.txt', 'a+') as f:
                f.write(f'{file_name}\n')
                f.write(f'{result}\n')
                f.write('\n')
            try:
                self.save_upload_message(file_name, '8', result)
            except Exception as e:
                print(f'创建上传信息失败,{str(e)}')
        else:
            result = res_dict['message']
            if result == '定稿数据状态异常,请联系专属顾问':
                result = '系统内已经存在受理通知书，请注意查看是否重复申报，并且要撤案！！！'
            erroritem = {}
            erroritem['wjm'] = f'{file_name}'
            erroritem['ycqk'] = f'{result}'
            erroritem['lczt'] = '流程为杨锦'
            self.pendingData.append(erroritem)
            with open(f'./上传文件记录/{today_date}需人工处理.txt', 'a+') as f:
                f.write(f'{file_name}\n')
                f.write(f'{result}\n')
                f.write(f'流程为杨锦\n')
                f.write('\n')
            try:
                self.save_upload_message(file_name, '8', result)
            except Exception as e:
                print(f'创建上传信息失败,{str(e)}')

    @retry(stop_max_attempt_number=10)
    def upload_files(self, item, id, today_date, url_str):
        """上传接口, 此接口上传（补正，初审，实审，驳回，审查意见）文件"""
        files = {}
        files['file'] = open("{}".format(item['file']), "rb")
        url = url_str.format(id)
        data = {
            'finals': id,
            'type': item['type'],
            'token': self.token,
        }
        print("============+++++++++++++++++++++++++", url, id)
        r = requests.post(url=url, files=files, data=data, headers=self.headers, verify=False, timeout=60)
        res_dict = json.loads(r.text)
        if res_dict['status'] == 'success':
            result = '上传成功！'
            with open(f'./上传文件记录/{today_date}上传文件成功.txt', 'a+') as f:
                f.write(f'{item["name"]}\n')
                f.write(f"{data}\n")
                f.write(f'{result}\n')
                f.write('\n')
            try:
                self.save_upload_message(item["name"], item['type'], result)
            except Exception as e:
                print(f'创建上传信息失败,{str(e)}')
        else:
            result = res_dict['message']
            erroritem = {}
            erroritem['wjm'] = f'{item["name"]}'
            erroritem['ycqk'] = f'{result}'
            erroritem['lczt'] = '流程为杨锦'
            self.pendingData.append(erroritem)
            with open(f'./上传文件记录/{today_date}需人工处理.txt', 'a+') as f:
                f.write(f'{item["name"]}\n')
                f.write(f'{result}\n')
                f.write(f'流程为杨锦\n')
                f.write('\n')
                try:
                    self.save_upload_message(item["name"], item['type'], result)
                except Exception as e:
                    print(f'创建上传信息失败,{str(e)}')


    def upload_patent_zs(self, file, file_name, today_date, zs_url):
        """
        上传证书，file: 文件路径、file_name: 证书名
        """
        id = self.get_id(file_name.split("_")[-2])
        url = zs_url.format(id)
        files = {'file': open("{}".format(file), "rb")}
        data = {
            'finals': id,
            'token': self.token,
        }
        print("data: ", data)
        r = requests.post(url=url, files=files, data=data, headers=self.headers, verify=False)
        res_dict = json.loads(r.text)
        if res_dict['status'] == 'success':
            result = '上传成功！'
            with open(f'./上传文件记录/{today_date}上传文件成功.txt', 'a+') as f:
                f.write(f'{file_name}\n')
                f.write(f'{result}\n')
                f.write('\n')
            try:
                self.save_upload_message(file_name, '7', result)
            except Exception as e:
                print(f'创建上传信息失败,{str(e)}')
        else:
            result = res_dict['message']
            erroritem = {}
            erroritem['wjm'] = f'{file_name}'
            erroritem['ycqk'] = f'{result}'
            erroritem['lczt'] = '流程为杨锦'
            self.pendingData.append(erroritem)
            with open(f'./上传文件记录/{today_date}需人工处理.txt', 'a+') as f:
                f.write(f'{file_name}\n')
                f.write(f'{result}\n')
                f.write('流程为杨锦\n')
                f.write('\n')
            try:
                self.save_upload_message(file_name, '7', result)
            except Exception as e:
                print(f'创建上传信息失败,{str(e)}')

    def upload_abnormal(self, file, file_name, today_date, url):
        """上传异常文件、包括专利权终止通知书、手续合格通知书"""
        application_number = file.split("_")[-2]
        file_li = []
        file_li.append(('file[]', open("{}".format(file), "rb")))
        if file.split("_")[-3] == "专利权终止通知书":
            file_type = "2"
        else:
            file_type = '1'
        data = {"file_type": file_type, 'application_number': application_number}
        r = requests.post(url=url, headers=self.headers, data=data, files=file_li)
        res_dict = json.loads(r.text)
        if res_dict['code'] == 200:
            result = "上传成功"
            with open(f'./上传文件记录/{today_date}上传文件成功.txt', 'a+') as f:
                f.write(f'{file_name}\n')
                f.write(f"{data}\n")
                f.write(f'{result}\n')
                f.write('\n')
            try:
                self.save_upload_message(file_name, file_type, result)
            except Exception as e:
                print(f'创建上传信息失败,{str(e)}')
        else:
            erroritem = {}
            erroritem['wjm'] = f'{file_name}'
            erroritem['ycqk'] = f"{application_number}"
            erroritem['lczt'] = f"{res_dict['message']}"
            self.pendingData.append(erroritem)
            with open(f"./上传文件记录/{today_date}需人工处理.txt", "w") as fw:
                fw.write(f'{file_name}\n')
                fw.write(f"{application_number}\n")
                fw.write(f"{res_dict['message']}\n")
            # 1016新添加的  上传需要人工处理的文件到服务器
            try:
                self.save_upload_message(file_name, file_type, res_dict['message'])
            except Exception as e:
                print(f'创建上传信息失败,{str(e)}')

    def upload_other_files(self, file, file_name, today_date, url):
        """
        上传其他文件，例如：文件不受理通知书、缴费通知书、缴纳申请费通知书、等。
        """
        application_number = file_name.split("_")[-2]
        country_send_time = file_name.split("_")[0]
        file_type = file_name.split("_")[-3]
        limit_time = '无'
        if '文件不受理通知书' in file_name:
            order_num = file_name.split("_")[-5]
            application_number = self.select_info(order_num)
        if "办理恢复权利手续补正" in file_name:
            limit_time = '1个月'
        if '视为未委托专利代理机构' in file_name:
            limit_time = '2个月'
        if '非正常专利申请初步确认' in file_name:
            limit_time = '15日'
        if '退款审批' in file_name:
            limit_time = '2个月'
        if '缴纳申请费通知书' in file_name:
            limit_time = '2个月'
        if '缴费通知书' in file_name:
            limit_time = '1个月'
        file = {"file": open(f'{file}', 'rb')}
        data = {
            'application_number': application_number.replace("-1", "").replace("-2", "").replace("-3", ""),
            'time_limit': limit_time,
            'country_send_time': country_send_time,
            'file_type': file_type,
        }
        r = requests.post(url=url, data=data, headers=self.headers, files=file)
        res_dict = json.loads(r.text)
        if res_dict['status'] == 'success':
            result = '上传成功！'
            with open(f'./上传文件记录/{today_date}上传文件成功.txt', 'a+') as f:
                f.write(f'{file_name}\n')
                f.write(f'{data}\n')
                f.write(f'{result}\n')
                f.write('\n')
            try:
                self.save_upload_message(file_name, file_type, result)
            except Exception as e:
                print(f'创建上传信息失败,{str(e)}')
        else:
            erroritem = {}
            erroritem['wjm'] = f'{file_name}'
            erroritem['ycqk'] = f"{data}"
            erroritem['lczt'] = f"{res_dict}"
            self.pendingData.append(erroritem)
            with open(f'./上传文件记录/{today_date}需人工处理.txt', 'a+') as f:
                f.write(f'{file_name}\n')
                f.write(f"{data}\n")
                f.write(f"{res_dict}\n")

    def select_info(self, order):
        sql = f"SELECT application_number FROM finals WHERE order_number = '{order}'"
        self.cursor.execute(sql)
        data = self.cursor.fetchall()
        try:
            sqh = data[0][0].replace("ZL", '')
        except:
            sqh = ''
        return sqh

    def main_fun(self):
        date = time.strftime("%Y%m%d")
        # date = '22222222'
        today_date = time.strftime("%Y-%m-%d", time.localtime())
        cur_file = os.getcwd()  # 当前工作路径
        pathZip = os.path.join(cur_file, date)  # 拼接路径并创建
        pdf_main_path = os.path.join(pathZip, "PDF")
        if not os.path.exists(pdf_main_path):
            os.mkdir(pdf_main_path)

        pathZip = os.path.join(pathZip, '压缩包')
        if not os.path.exists(pathZip):
            os.mkdir(pathZip)
        url_dir = UrlContainer(self.environment).url_class()  # 获取当前环境对应的接口路由
        self.parse_pdf(pathZip, pdf_main_path, today_date, url_dir)
        print("今日文件处理完毕")

        self.dataToProcessedManually(self.pendingData, today_date)


if __name__ == '__main__':
    # environment = input("请确认当前程序运行环境：")
    environment = "product"  # product 正式环境、test 测试环境

    unzip_file(environment).main_fun()
